package me.yangbajing.model

import org.squeryl.KeyedEntity
import org.joda.time.DateTime
import org.bson.types.ObjectId

import net.liftweb.common.Box

import yangbajing.persistence.SquerylEntrypoint._
import yangbajing.util.Pagination
import yangbajing.util.Imports.Y

object MCategory {
  def getIdByName(name: String): Box[String] =
    transaction(from(Entities.categories)(c => where(c.name === name) select c.id).headOption)

  def modify(id: String, category: String): Box[Int] =
    Y.tryBox {
      require(Y.nonBlank(id), "id 不能为空")
      require(Y.nonBlank(category), "category 不能为空")

      transaction(update(Entities.categories)(c =>
        where(c.id === id) set (c.name := category)))
    }

  def removeById(id: String): Box[Int] =
    Y.tryBox {
      require(Y.nonBlank(id), "id 不能为空")
      transaction(Entities.categories.deleteWhere(_.id === id))
    }

  def insert(category: String, creator: String): Box[MCategory] =
    Y.tryBox {
      require(Y.nonBlank(category), "category 不能为空")
      transaction(Entities.categories insert new MCategory(category, creator))
    }

  def idNames(): List[(String, String)] =
    transaction(from(Entities.categories)(c =>
      select(c.id -> c.name) orderBy(c.sort_by.desc, c.id.desc)).toList)

  def findOne(id: String): Box[MCategory] =
    Y.tryBox {
      require(Y.nonBlank(id), "id 不能为空")

      transaction(from(Entities.categories)(c =>
        where(
          if (ObjectId.isValid(id)) c.id === id else c.name === id
        ) select c).single)
    }

  def size(creator: Option[String] = None): Long =
    transaction(from(Entities.categories)(c =>
      _where(c, creator
      ) compute count(c.id)))

  def findAll(offset: Int, limit: Int, creator: Option[String] = None): List[MCategory] =
    transaction(from(Entities.categories)(c =>
      _where(c, creator
      ) select c orderBy(c.sort_by.desc, c.id.desc)).page(offset, limit).toList
    )

  private def _where(c: MCategory, creator: Option[String] = None) =
    where(
      c.creator === creator.?
    )

  def pagination(_curPage: Int, _limit: Int, creator: Option[String] = None) =
    new Pagination[MCategory] {
      val curPage = _curPage
      val limit = _limit
      val total = size(creator = creator)
      val page = findAll(offset, limit, creator)
    }
}

case class MCategory(
                      name: String,
                      creator: String,
                      sort_by: Int = 0,
                      created_at: DateTime = DateTime.now(),
                      id: String = ObjectId.get.toString) extends KeyedEntity[String]
